package encaps.action;

import encaps.entities.Grant;
import encaps.entities.UserLocal;
import encaps.entities.UserLocalHome;
import encaps.resources.Labels;
import encaps.security.RoleManager;
import encaps.utils.DataAccessException;
import encaps.utils.EntityUtil;
import encaps.utils.InitializationException;
import encaps.utils.XMLHelper;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class ViewProfileAction extends Action {

    public static final String VIEW_PROFILE = "viewProfile";
    private ActionContext actionContext;

    public ViewProfileAction(ActionContext context, Grant requiredGrant) {
        this.actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    public Element execute() throws ActionExecutionException {
        try {
            UserLocalHome userHome = EntityUtil.getUserHome();
            UserLocal user = userHome.findByLogin(actionContext.getUserLogin());
            Element userElement = XMLHelper.toXMLElement(user, Labels.getLabel(Labels.YOUR_PROFILE), RoleManager.getRoleManager().getRole(actionContext.getUserRole()), false);
            return userElement;
        } catch (InitializationException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (DataAccessException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (NamingException ex) {
            throw new ActionExecutionException("Cannot find UserLocalHome object", ex);
        } catch (FinderException ex) {
            throw new ActionExecutionException("User '" + actionContext.getUserLogin() + "' not found", ex);
        }
    }
}
